package com.ruoyi.cms.controller.admin;

import com.github.pagehelper.PageInfo;
import com.ruoyi.cms.common.BaseController;
import com.ruoyi.cms.domain.Archives;
import com.ruoyi.cms.domain.Category;
import com.ruoyi.cms.domain.Theme;
import com.ruoyi.cms.domain.System;
import com.ruoyi.cms.domain.vo.CategoryVO;
import com.ruoyi.cms.exception.CmsException;
import com.ruoyi.cms.exception.TemplateNotFoundException;
import com.ruoyi.cms.exception.TemplateReadException;
import com.ruoyi.cms.service.ArchivesService;
import com.ruoyi.cms.service.CategoryService;
import com.ruoyi.cms.service.SystemService;
import com.ruoyi.cms.service.ThemeService;
import com.ruoyi.cms.taglib.ParseEngine;
import com.ruoyi.cms.util.*;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import jodd.util.StringUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.websocket.EncodeException;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/cms/statics")
public class StaticController extends BaseController {
    @Autowired
    private ThemeService themeService;
    @Autowired
    private FileConfiguration fileConfiguration;
    @Autowired
    private ParseEngine parseEngine;
    @Autowired
    private SystemService systemService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ArchivesService archivesService;

    @GetMapping("loadParam")
    public R<Map<String,Object>> loadParam() {
        Map<String, Object> result = new HashMap<>();
        Theme currentTheme = themeService.getCurrentTheme();
        result.put("currentTheme", currentTheme);
        return R.ok(result);
    }

    @PostMapping("generateIndex")
    public R<String> generateIndex() throws CmsException, IOException, EncodeException {
        System system = systemService.getSystem();
        Theme theme = themeService.getCurrentTheme();
        String templatePath = theme.getThemePath() + "/index.html";
        String templateDir = fileConfiguration.getResourceDir() + "/templates/";
        String path = templateDir + templatePath;
        File template = new File(path);
        if(!template.exists() || template.isDirectory()) {
            throw new TemplateNotFoundException(
                ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getCode(),
                ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getMessage(),
                "请仔细检查" + template.getAbsolutePath() + "文件，或检查application.yml中的资源目录配置项（web.resource-path）。");
        }
        String newHtml = "";
        try {
            String html = FileUtils.readFileToString(template, "UTF-8");
            newHtml = parseEngine.generate(html);
            File file = new File(fileConfiguration.getResourceDir() +"/"+ system.getStaticdir() + "/index.html");
            FileUtils.write(file, newHtml, "UTF-8");
        } catch (IOException e) {
            throw new TemplateReadException(
                ExceptionEnum.TEMPLATE_READ_EXCEPTION.getCode(),
                ExceptionEnum.TEMPLATE_READ_EXCEPTION.getMessage(),
                "请仔细检查模版文件，或检查application.yml中的资源目录配置项（web.resource-path）。");
        }
        return R.ok();
    }

    @PostMapping("generateCategory")
    public ResponseResult generateCategory(@RequestBody CategoryVO categoryVo) throws CmsException, IOException, EncodeException {
        String id = categoryVo.getId();
        String updateChild = categoryVo.getUpdateChild();//是否生成子栏目
        if(StringUtil.isBlank(id)) {//生成全部
            List<Category> all = categoryService.queryAll();
            for (Iterator iterator = all.iterator(); iterator.hasNext();) {
                Category categoryWithBLOBs = (Category) iterator.next();
                buildCategoryHTML(categoryWithBLOBs, "ALL");
            }
        }else {//指定栏目生成
            Category categoryWithBLOBs = categoryService.selectById(id);
            buildCategoryHTML(categoryWithBLOBs, updateChild);
        }
        return ResponseResult.Factory.newInstance(Boolean.TRUE, StateCodeEnum.HTTP_SUCCESS.getCode(), null, StateCodeEnum.HTTP_SUCCESS.getDescription());
    }

    /**
     * 构建栏目html并生成文件
     * @param categoryWithBLOBs
     * @throws TemplateNotFoundException
     * @throws TemplateReadException
     * @throws EncodeException
     * @throws IOException
     */
    private void buildCategoryHTML(Category categoryWithBLOBs, String updateChild)
        throws CmsException, EncodeException, IOException {
        System system = systemService.getSystem();
        Theme theme = themeService.getCurrentTheme();

        if("ALL".equals(updateChild) || "1".equals(updateChild)) {
            List<Category> childrenList = categoryService.selectByParentId(categoryWithBLOBs.getId());
            if(childrenList != null && childrenList.size() > 0) {
                for(int i = 0;i < childrenList.size();i++) {
                    buildCategoryHTML(childrenList.get(i), updateChild);
                }
            }
        }

        String templateDir = fileConfiguration.getResourceDir() + "/templates/";
        StringBuffer templatePath = new StringBuffer();
        templatePath.append(theme.getThemePath());
        if(categoryWithBLOBs.getCatModel() == 1) {
            templatePath.append(categoryWithBLOBs.getCoverTemp());
        }else if(categoryWithBLOBs.getCatModel() == 2) {
            templatePath.append(categoryWithBLOBs.getListTemp());
        }else if(categoryWithBLOBs.getCatModel() == 3) {
            return;
        }
        String newHtml = "";
        try {
            String path = templateDir + templatePath;
            java.lang.System.out.println("模板地址:==="+path);
            File template = null;
            try {
                template = new File(path);
            }catch (Exception e){
                e.printStackTrace();
            }
            if(!template.exists() || template.isDirectory()) {
                throw new TemplateNotFoundException(
                    ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getCode(),
                    ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getMessage(),
                    "请仔细检查" + template.getAbsolutePath() + "文件，或检查application.yml中的资源目录配置项（web.resource-path）。");
            }
            String html = FileUtils.readFileToString(template, "UTF-8");

            newHtml = parseEngine.generate(html);
            newHtml = parseEngine.generateCategory(newHtml, categoryWithBLOBs.getCode());

            String newCreateHtml = new String(newHtml);

            /**
             * 如果为列表栏目，则循环生成分页页面
             */
            if(categoryWithBLOBs.getCatModel() == 2) {//列表
                SearchEntity params = new SearchEntity();
                params.setPageNum(1);
                params.setPageSize(StringUtils.isBlank(categoryWithBLOBs.getPageSize()) ? 10 : categoryWithBLOBs.getPageSize());
                Map<String,Object> entity = new HashMap<String,Object>();
                entity.put("cid", categoryWithBLOBs.getCode());
                params.setEntity(entity);
                PageInfo<Map<String, Object>> pageInfo = archivesService.queryListByPage(params);
                int total = pageInfo.getPages();
                int pageNum = pageInfo.getPageNum();
                int pageSize = pageInfo.getPageSize();
                if(total <= 0) {//如果列表无数据，则生成空页面
                    newHtml = new String(newCreateHtml);
                    newHtml = parseEngine.generatePageList(newHtml, categoryWithBLOBs.getCode(), pageNum, pageSize);
                    String catDir = URLUtils.getCategoryDir(categoryWithBLOBs);
                    String fileName = URLUtils.parseFileName(categoryWithBLOBs, pageNum);
                    File file = new File(fileConfiguration.getResourceDir() + "/"+system.getStaticdir() + catDir + fileName);
                    FileUtils.write(file, newHtml, "UTF-8");
                }else {//如果列表有数据，则生成全部页面
                    while (pageNum <= total) {
                        newHtml = new String(newCreateHtml);
                        newHtml = parseEngine.generatePageList(newHtml, categoryWithBLOBs.getCode(), pageNum, pageSize);
                        String catDir = URLUtils.getCategoryDir(categoryWithBLOBs);
                        String fileName = URLUtils.parseFileName(categoryWithBLOBs, pageNum);
                        File file = new File(fileConfiguration.getResourceDir() +"/"+ system.getStaticdir() + catDir + fileName);
                        java.lang.System.out.println("列表：==="+file.getAbsolutePath());
                        FileUtils.write(file, newHtml, "UTF-8");
                        if(pageNum == 1) {
                            buildArticleHTML(categoryWithBLOBs);
                        }
                        pageNum++;
                    }
                }
            }else {//封面
                String catDir = URLUtils.getCategoryDir(categoryWithBLOBs);
                File file = new File(fileConfiguration.getResourceDir() +"/"+ system.getStaticdir() + catDir + "/index.html");
                java.lang.System.out.println("封面：==="+file.getAbsolutePath());
                FileUtils.write(file, newHtml, "UTF-8");
            }
        } catch (IOException e) {
            throw new TemplateReadException(
                ExceptionEnum.TEMPLATE_READ_EXCEPTION.getCode(),
                ExceptionEnum.TEMPLATE_READ_EXCEPTION.getMessage(),
                "请仔细检查模版文件，或检查application.yml中的资源目录配置项（web.resource-path）。");
        }
    }

    /**
     * 生成栏目下的文档
     * @param categoryWithBLOBs
     * @throws TemplateNotFoundException
     * @throws TemplateReadException
     * @throws EncodeException
     * @throws IOException
     */
    private void buildArticleHTML(Category categoryWithBLOBs)
        throws CmsException, EncodeException, IOException {
        System system = systemService.getSystem();
        Theme theme = themeService.getCurrentTheme();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

        try {
            String templateDir = fileConfiguration.getResourceDir() + "/templates/";
            StringBuffer templatePath = new StringBuffer();
            templatePath.append(theme.getThemePath());

            if(categoryWithBLOBs.getCatModel() == 1) {
                return;
            }else if(categoryWithBLOBs.getCatModel() == 2) {
                templatePath.append(categoryWithBLOBs.getArticleTemp());
            }

            String path = templateDir + templatePath;
            File template = new File(path);
            if(!template.exists()) {
                throw new TemplateNotFoundException(
                    ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getCode(),
                    ExceptionEnum.TEMPLATE_NOTFOUND_EXCEPTION.getMessage(),
                    "请仔细检查" + template.getAbsolutePath() + "文件，或检查application.yml中的资源目录配置项（web.resource-path）。");
            }
            String newHtml = "";
            String html = FileUtils.readFileToString(template, "UTF-8");
            String catDir = URLUtils.getCategoryDir(categoryWithBLOBs);

            List<Archives> allArt = this.archivesService.queryAll(categoryWithBLOBs.getId());

            for (int i = 0; i < allArt.size(); i++) {//循环生成文档
                Archives archives = allArt.get(i);
                Date createTime = archives.getCreateTime();
                String dateDir = sdf.format(createTime);
                newHtml = parseEngine.generate(html);
                newHtml = parseEngine.generateCategory(newHtml, categoryWithBLOBs.getCode());
                newHtml = parseEngine.parseArticle(newHtml, archives.getId());
                newHtml = parseEngine.generatePrevAndNext(newHtml, archives.getId());
                File file = new File(fileConfiguration.getResourceDir() + "/" +system.getStaticdir() + catDir + "/" + dateDir + "/" + archives.getId() + ".html");
                FileUtils.write(file, newHtml, "UTF-8");
            }
        }catch (Exception e) {
            throw new TemplateReadException(
                ExceptionEnum.TEMPLATE_READ_EXCEPTION.getCode(),
                ExceptionEnum.TEMPLATE_READ_EXCEPTION.getMessage(),
                "请仔细检查模版文件，或检查application.yml中的资源目录配置项（web.resource-path）。");
        }
    }

}
